package com.sam.im.heiqun.uis.activities;

import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.NewFriendAdpter;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 邀请添加好友
 */
public class NewFriendsActivity extends BaseSwipeBackActivity implements NewFriendAdpter.NewFriendListClickListener {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.right2)
    ImageView right2;
    @BindView(R.id.new_friends_list)
    RecyclerView newFriendsList;
    @BindView(R.id.activity_new_friends)
    LinearLayout activityNewFriends;
    private NewFriendAdpter mNewFriendAdpter;
    private PGService mPGservice;
    private String destType = "1";
    private String groupId;
    private String friendGroupId = "";
    private List<MessageEntivity> messageEntivities;

    @Override
    public int getContentViewId() {
        return R.layout.activity_new_friends;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.new_friend);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        UserEntivity userEntivity = ToolsUtils.getUser();

        right2.setBackgroundResource(R.drawable.delete);
        right2.setVisibility(View.VISIBLE);

        mPGservice = PGService.getInstance();
        mNewFriendAdpter = new NewFriendAdpter(this);
        mNewFriendAdpter.setItemClickListener(this);
        newFriendsList.setLayoutManager(new LinearLayoutManager(this));
        newFriendsList.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        newFriendsList.setAdapter(mNewFriendAdpter);
        messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid = ? and (type = ? or type=?)"
                , userEntivity.getId() + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.NOTICE_OF_APPLY_FRIEND + "");

        mNewFriendAdpter.refresh(messageEntivities);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      //  int id = (int) destid;
        notificationManager.cancel(0);//注销系统通知 系统通知id为0
    }

    @OnClick({R.id.pre_v_back, R.id.right, R.id.right2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back: {
                scrollToFinishActivity();
                break;
            }
            case R.id.right://添加
                startActivity(SeachFriendsActivity.class);
                break;
            case R.id.right2://
                AlertDialog.Builder builder = new AlertDialog.Builder(NewFriendsActivity.this);
                builder.setTitle(getResources().getString(R.string.tip));
                builder.setMessage(getResources().getString(R.string.delete_ok));
                builder.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (null!=messageEntivities && messageEntivities.size() > 0){
                            for (int i = 0; i < messageEntivities.size(); i++) {
                                messageEntivities.get(i).delete();
                            }
                        }
                        messageEntivities.clear();
                        mNewFriendAdpter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
        }
    }

    @Override
    public void onAgreeNewFriendClick(View view, final int position, int type) {
        if (0 == type) {
            Bundle bundle = new Bundle();
//            bundle.putSerializable("friendInfo", mFriends.get(position));
            bundle.putLong("id", messageEntivities.get(position).getDestid());
            bundle.putInt("type", 2);
            startActivity(FriendDetailActivity.class, bundle);
        }else if (1 == type) {
            //删除好友申请实体
            MessageEntivity.deleteAll(MessageEntivity.class, "type=? and fromid=?", new String[]{"" + messageEntivities.get(position).getType(), "" + messageEntivities.get(position).getFromid()});
            showToast(getResources().getString(R.string.refuse_frdapply_success));
            scrollToFinishActivity();
            hideProgress();
        } else {
            showProgress(getResources().getString(R.string.commiting));
            mPGservice.acceptRequest("" + messageEntivities.get(position).getDestid(), destType, friendGroupId, groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ImFriendEntivity>() {
                @Override
                protected void onResultError(ApiException ex) {
                    showToast(getResources().getString(R.string.add_defeat));
                    hideProgress();
                }

                @Override
                public void onNext(ImFriendEntivity entivity) {
                    //删除好友申请实体
                    MessageEntivity.deleteAll(MessageEntivity.class, "type=? and fromid=?", new String[]{"" + messageEntivities.get(position).getType(), "" + messageEntivities.get(position).getFromid()});
                    //添加本地好友数据
                    if (!ToolsUtils.isMyFriendForId(entivity.getId())) {
                        getUserById(entivity.getId() + "");
                    }

                }
            });
        }
    }

    /**
     * 根据好id查询详情（此处用于添加好友），查询完成后保存数据库
     *
     * @param destid
     */
    private void getUserById(final String destid) {
        final String fromid = ToolsUtils.getMyUserId();
        mPGservice.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivity) {
                UserEntivity userEntivity = ToolsUtils.getUser();
                //更新数据库
                mFriendEntivity.setCurrentid(userEntivity.getId());
                mFriendEntivity.setIsBlack("0");
                mFriendEntivity.save();

                //刷新好友页面数据
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                showToast(getResources().getString(R.string.add_success));
                scrollToFinishActivity();
                hideProgress();
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
            }
        });
    }

}
